package com.example.classweatherforecast

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import kotlin.math.min
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {
    private lateinit var queue: RequestQueue
    private lateinit var weather1: TextView
    private lateinit var weather2: TextView
    private lateinit var weather3: TextView
    private lateinit var weather4: TextView
    private lateinit var weather5: TextView
    private lateinit var linearLayout: LinearLayout
    private lateinit var citySpinner: Spinner
    private lateinit var refreshButton: Button
    private lateinit var weekCalculator: WeekCalculator
    private lateinit var cityCodeManager: CityCodeManager
    private lateinit var currentCityCode: String
    private var responseStr: String = ""  // 存储完整的API响应字符串

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 隐藏默认的标题栏
        supportActionBar?.hide()
        setContentView(R.layout.activity_main)

        // 初始化队列
        queue = Volley.newRequestQueue(this)
        weather1 = findViewById(R.id.textview_w1)
        weather2 = findViewById(R.id.textview_w2)
        weather3 = findViewById(R.id.textview_w3)
        weather4 = findViewById(R.id.textview_w4)
        weather5 = findViewById(R.id.textview_w5)
        linearLayout = findViewById(R.id.lin_01)
        citySpinner = findViewById(R.id.spinner_city)
        refreshButton = findViewById(R.id.button_refresh)
        weekCalculator = WeekCalculator()
        cityCodeManager = CityCodeManager()

        // 初始化城市选择器
        initCitySpinner()

        // 默认加载重庆的天气
        currentCityCode = "101040100"
        loadWeatherData(currentCityCode)

        // 刷新按钮点击事件
        refreshButton.setOnClickListener {
            val selectedCity = citySpinner.selectedItem.toString()
            val cityCode = cityCodeManager.getCityCode(selectedCity)
            if (cityCode != null) {
                currentCityCode = cityCode
                loadWeatherData(currentCityCode)
                Toast.makeText(this, "已刷新${selectedCity}天气数据", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun initCitySpinner() {
        // 获取所有城市列表
        val cities = cityCodeManager.getAllCities()
        
        // 创建适配器
        val adapter = ArrayAdapter(
            this,
            android.R.layout.simple_spinner_item,
            cities
        )
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        
        // 设置适配器
        citySpinner.adapter = adapter
        
        // 设置默认选中重庆
        val defaultCityIndex = cities.indexOf("重庆")
        if (defaultCityIndex >= 0) {
            citySpinner.setSelection(defaultCityIndex)
        }
        
        // 设置选择监听器
        citySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View,
                position: Int,
                id: Long
            ) {
                val selectedCity = parent.getItemAtPosition(position).toString()
                val cityCode = cityCodeManager.getCityCode(selectedCity)
                if (cityCode != null) {
                    // 确保只在选择变化时加载数据
                    if (cityCode != currentCityCode) {
                        currentCityCode = cityCode
                        loadWeatherData(currentCityCode)
                        Toast.makeText(this@MainActivity, "已切换到${selectedCity}", Toast.LENGTH_SHORT).show()
                    }
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>) {
                // 未选择时的处理
            }
        }
    }

    private fun loadWeatherData(cityCode: String) {
        // 显示加载中提示
        Toast.makeText(this, "正在加载天气数据...", Toast.LENGTH_SHORT).show()
        
        try {
            // 直接使用硬编码的URL（天气API的基础URL）
            val baseUrl = "http://t.weather.sojson.com/api/weather/city"
            val finalUrl = "$baseUrl/$cityCode"
            
            Log.d("WeatherDebug", "请求URL: $finalUrl")

            val jsonObjectRequest = JsonObjectRequest(
                Request.Method.GET, finalUrl, null,
                { response ->
                    try {
                        // 保存完整的响应字符串
                        responseStr = response.toString()
                        Log.d("WeatherDebug", "获取到响应数据: $responseStr")
                        
                        // 处理响应数据
                        // 先检查返回码
                        val status = response.getInt("status")
                        if (status == 200) {
                            val data = response.getJSONObject("data")
                            val forecast = data.getJSONArray("forecast")
                            
                            // 更新当前天气信息
                            updateCurrentWeather(data)

                            // 更新未来天气信息
                            updateForecastWeather(forecast)
                            
                            // 获取城市名称
                            val cityName = cityCodeManager.getCityName(cityCode)
                            Toast.makeText(this, "${cityName}天气数据加载成功", Toast.LENGTH_SHORT).show()
                        } else {
                            val message = response.optString("message", "数据获取失败")
                            Log.e("WeatherError", "API返回错误状态: $status, 消息: $message")
                            Toast.makeText(this, "天气数据获取失败: $message", Toast.LENGTH_SHORT).show()
                        }
                    } catch (e: JSONException) {
                        Log.e("WeatherError", "JSON解析错误: ${e.message}")
                        Log.e("WeatherError", "错误堆栈: ${e.stackTrace.joinToString("\n")}")
                        Toast.makeText(this, "天气数据解析错误，请稍后重试", Toast.LENGTH_SHORT).show()
                    }
                },
                { error ->
                    Log.e("WeatherError", "网络请求错误: ${error.message}")
                    if (error.networkResponse != null) {
                        Log.e("WeatherError", "HTTP状态码: ${error.networkResponse.statusCode}")
                        Toast.makeText(this, "网络请求失败，HTTP状态码: ${error.networkResponse.statusCode}", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this, "网络请求失败，请检查网络连接", Toast.LENGTH_SHORT).show()
                    }
                }
            )

            // 将请求添加到队列
            queue.add(jsonObjectRequest)
        } catch (e: Exception) {
            Log.e("WeatherError", "加载天气数据时发生错误: ${e.message}")
            Log.e("WeatherError", "错误堆栈: ${e.stackTrace.joinToString("\n")}")
            Toast.makeText(this, "加载天气数据失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    private fun updateCurrentWeather(data: JSONObject) {
        try {
            // 从data对象中获取wendu
            val wendu = data.optString("wendu", "--")
            
            // 获取城市名称（简化处理，直接从CityCodeManager获取）
            val city = cityCodeManager.getCityName(currentCityCode).ifEmpty { "未知城市" }
            
            // 从forecast数组的第一个元素获取今天的天气信息
            val forecastArray = data.optJSONArray("forecast")
            var high = "--"
            var low = "--"
            var type = "--"
            var fengxiang = "--"
            var fengli = "--"
            
            if (forecastArray != null && forecastArray.length() > 0) {
                val todayInfo = forecastArray.optJSONObject(0)
                if (todayInfo != null) {
                    high = todayInfo.optString("high", "--")
                    low = todayInfo.optString("low", "--")
                    type = todayInfo.optString("type", "--")
                    fengxiang = todayInfo.optString("fx", todayInfo.optString("fengxiang", "--"))
                    fengli = todayInfo.optString("fl", todayInfo.optString("fengli", "--"))
                }
            }

            // 优化UI显示，确保温度格式一致
            val formattedWendu = if (wendu != "--") "$wendu°C" else "--°C"
            
            // 更新UI
            weather1.text = formattedWendu
            
            // 从数据中获取空气质量信息
            val quality = data.optString("quality", "优")
            val aqi = data.optJSONObject("aqi")?.optInt("value", 0) ?: 0
            weather2.text = "$city   PM:$aqi $quality"
            
            // 优化温度显示，确保包含温度单位
            weather3.text = "$type    $low~$high°C"
            weather4.text = "$fengxiang   $fengli"

            // 更新日期和星期
            val calendar = Calendar.getInstance()
            val dateFormat = SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA)
            val dateStr = dateFormat.format(calendar.time)
            val weekday = weekCalculator.getWeekdayFromDate(dateStr)
            weather5.text = "$dateStr   $weekday"

            Log.d("WeatherDebug", "成功更新当前天气信息: $city, $formattedWendu, $type")

        } catch (e: JSONException) {
            Log.e("WeatherError", "更新当前天气错误: ${e.message}")
            Log.e("WeatherError", "错误堆栈: ${e.stackTrace.joinToString("\n")}")
            
            // 错误情况下显示默认值，确保UI不会空白
            weather1.text = "--°C"
            weather2.text = "${cityCodeManager.getCityName(currentCityCode)}   数据加载失败"
            weather3.text = "--  --"
            weather4.text = "--  --"
            
            val calendar = Calendar.getInstance()
            val dateFormat = SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA)
            val dateStr = dateFormat.format(calendar.time)
            weather5.text = dateStr
            
            Toast.makeText(this, "更新天气信息失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun updateForecastWeather(forecast: JSONArray) {
        try {
            Log.d("WeatherDebug", "开始更新未来天气预报，共${forecast.length()}天")
            
            // 清除现有的子视图
            linearLayout.removeAllViews()

            // 添加未来几天的天气信息（从第二天开始，最多显示4天）
            val maxDaysToShow = min(forecast.length() - 1, 4)
            
            // 如果没有数据，显示提示信息
            if (maxDaysToShow < 1) {
                val noDataText = TextView(this)
                noDataText.text = "暂无预报数据"
                noDataText.setTextColor(android.graphics.Color.WHITE)
                noDataText.textSize = 16f
                noDataText.gravity = android.view.Gravity.CENTER
                noDataText.layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT
                )
                linearLayout.addView(noDataText)
                return
            }
            
            for (i in 1..maxDaysToShow) {
                try {
                    // 创建新的布局
                    val itemLayout = layoutInflater.inflate(R.layout.layout_item, null)

                    // 获取布局中的文本视图
                    val dayText = itemLayout.findViewById<TextView>(R.id.tv_1)
                    val typeText = itemLayout.findViewById<TextView>(R.id.tv_2)
                    val tempText = itemLayout.findViewById<TextView>(R.id.tv_3)

                    // 获取预报数据
                    val dayForecast = forecast.optJSONObject(i)
                    if (dayForecast != null) {
                        val type = dayForecast.optString("type", "--")
                        val high = dayForecast.optString("high", "--")
                        val low = dayForecast.optString("low", "--")

                        // 设置星期几（使用WeekCalculator）
                        val weekday = weekCalculator.getWeekdayAfterDays(i)
                        dayText.text = weekday

                        // 设置天气类型和温度，确保温度有单位
                        typeText.text = type
                        tempText.text = "$low~$high°C"

                        // 添加到线性布局
                        linearLayout.addView(itemLayout)
                        Log.d("WeatherDebug", "添加第${i}天天气预报: $weekday, $type, $low~$high°C")
                    }
                } catch (e: Exception) {
                    Log.e("WeatherError", "处理第${i}天天气预报时出错: ${e.message}")
                }
            }
        } catch (e: JSONException) {
            Log.e("WeatherError", "更新未来天气错误: ${e.message}")
            Log.e("WeatherError", "错误堆栈: ${e.stackTrace.joinToString("\n")}")
            
            // 显示错误信息
            linearLayout.removeAllViews()
            val errorText = TextView(this)
            errorText.text = "预报数据加载失败"
            errorText.setTextColor(android.graphics.Color.WHITE)
            errorText.textSize = 16f
            errorText.gravity = android.view.Gravity.CENTER
            errorText.layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
            )
            linearLayout.addView(errorText)
        }
    }
}